package com.mmm.nlp.impl;

import com.mmm.nlp.TextReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: Zhendong
 * Date: 4/21/13
 * Time: 12:36 AM
 * To change this template use File | Settings | File Templates.
 */
public class BufferedTextReader implements TextReader
{
  private static final int MINIMUM_BUFFERED_SIZE = 10000;
  private boolean isEOF = false;
  private char[] lastRemainingBuffer = new char[0];
  private BufferedReader reader;

  public BufferedTextReader(String inputFilePath) throws IOException
  {
    reader = new BufferedReader(new FileReader(inputFilePath));
  }

  @Override
  public boolean canRead() throws IOException
  {
    return !isEOF;
  }

  @Override
  public String read() throws IOException
  {
    StringBuilder sb = new StringBuilder();
    int singleChar;
    int count = 0;
    while (true) {
      singleChar = reader.read();
      count++;
      if(singleChar>=0)
      {
        if(count>=MINIMUM_BUFFERED_SIZE  && (singleChar=='\n' || singleChar== '\r'))
        {
          break;
        }
        else
        {
          sb.append((char)singleChar);
        }
      }
      else
      {
        isEOF = true;
        reader.close();
        break;
      }
    }
    return sb.toString();
  }
}